refactor(config): extract CLIParameter and restructure Args init flow#6569
refactor(config): extract CLIParameter and restructure Args init flow#6569vividctrlalt wants to merge 10 commits intotronprotocol:developfrom
Conversation
Extract all @parameter annotations from CommonParameter into a new CLIParameter class, removing JCommander dependency from common module. Refactor Args.setParam() into a four-step flow: parse CLI, apply config, apply CLI overrides via isAssigned(), init witness. Simplify clearParam() from ~160 lines to CommonParameter.reset().
- Restructure Args.setParam into 4-step flow: parse CLI, apply config, apply CLI overrides, init witnesses - Rename setParam(Config) to applyConfigParams, setCLIParameter to applyCLIParams for clarity - Extract WitnessInitializer into 3 static methods (initFromCLIPrivateKey, initFromCFGPrivateKey, initFromKeystore) with routing in Args - Remove password/privateKey/witnessAddress/help/version/configFilePath from CommonParameter — pass as method params instead of global state - Move JDK version check from Args to FullNode entry point - Extract Configuration.getByFileName for single-param config loading
| PARAMETER.maxHttpConnectNumber = cmd.maxHttpConnectNumber; | ||
| } | ||
| if (assigned.containsKey("--storage-db-directory")) { | ||
| PARAMETER.storageDbDirectory = cmd.storageDbDirectory; |
There was a problem hiding this comment.
In applyCLIParams(), 7 storage-related parameters are written only to intermediate fields on PARAMETER, not to the PARAMETER.storage object that is actually used at runtime. The approach in applyConfigParams() is correct (writing via PARAMETER.storage.setXxx()), and applyCLIParams() should be consistent with it.
Current code in applyCLIParams:
PARAMETER.storageDbDirectory = cmd.storageDbDirectory;
Should be changed to write directly to PARAMETER.storage, consistent with applyConfigParams:
PARAMETER.storage.setDbDirectory(cmd.storageDbDirectory);
Please check the relevant parameters.
There was a problem hiding this comment.
Thanks for catching this!
The existing tests did not cover the scenario where CLI storage parameters override config file values, which is why this bug went undetected after the refactor. Two test cases have been added to cover both the CLI-overrides-config and config-defaults-without-CLI scenarios.
Fixed in c4cb0e1. Please continue reviewing, thank you!
applyCLIParams() wrote 7 storage-related values to intermediate fields on CommonParameter instead of the Storage object that is actually used at runtime. Since applyConfigParams() runs first, these CLI values were silently ignored. - Remove 7 intermediate fields from CommonParameter - Simplify applyConfigParams() to read directly from config - Fix applyCLIParams() to write directly to PARAMETER.storage - Add tests for CLI-overrides-config and config-defaults scenarios
The test failed on ARM64 because Storage.getDbEngineFromConfig() silently overrode the user's config to ROCKSDB, which is unreasonable as it hides incompatible configuration from the user. Replace the silent override with an explicit validateConfig() check in Args that fails fast with IllegalArgumentException when LevelDB is configured on ARM64. This makes the incompatibility visible instead of silently swallowed.
…erride The validateConfig() approach caused 1273 test failures on ARM64 because most tests use config files with db.engine="LEVELDB" and setParam() was throwing IllegalArgumentException before any test logic could run. Restore the original silent override in Storage.getDbEngineFromConfig() which automatically switches to ROCKSDB on ARM64. Update the testConfigStorageDefaults test to be architecture-aware.
| helpStr.append("Name:\n\tFullNode - the java-tron command line interface\n"); | ||
| String programName = Strings.isNullOrEmpty(jCommander.getProgramName()) ? "FullNode.jar" : | ||
| jCommander.getProgramName(); | ||
| helpStr.append(String.format("%nUsage: java -jar %s [options] [seedNode <seedNode> ...]%n", |
There was a problem hiding this comment.
@vividctrlalt, here I noticed that seedNode was defined as a JCommander Main Parameter (without names attribute). But in applyCLIParams(), I didn't find where it's being copied to PARAMETER.seedNodes.
I might have missed it, but I couldn't find the handling in applyCLIParams(). Should we add something like:
if (!cmd.seedNodes.isEmpty()) {
PARAMETER.seedNodes = cmd.seedNodes;
}
Apologies if I misunderstood the code flow. Please let me know if I'm missing something! Thanks for your patience.
CLI seed nodes (JCommander main parameter) were not being copied to PARAMETER.seedNode after refactoring JCommander target from PARAMETER to CLIParameter. Inline loadSeeds into applyConfigParams and add seedNodes handling in applyCLIParams so CLI values properly override config file values. Co-Authored-By: Jeremy Zhang <warku123@users.noreply.github.com>
|
@warku123 Good catch! You're right — Fixed in 9c2c55b:
Thanks for the careful review! |
| PARAMETER.supportConstant = cmd.supportConstant; | ||
| } | ||
| if (assigned.containsKey("--max-energy-limit-for-constant")) { | ||
| PARAMETER.maxEnergyLimitForConstant = cmd.maxEnergyLimitForConstant; |
There was a problem hiding this comment.
We should also has the value check as the applyConfigParams(previously applyConfigParams) does:
PARAMETER.maxEnergyLimitForConstant = max(3_000_000L, cmd.maxEnergyLimitForConstant, true);
There was a problem hiding this comment.
Thanks for the review! A couple of notes on this:
-
This is actually a pre-existing issue, not something introduced by this refactor. The original code before the refactor also directly assigns
cmd.maxEnergyLimitForConstantwithout themax()check — so this is outside the scope of the current refactoring PR. -
The long-term direction is to move towards a fully configuration-file-driven approach (similar to Nginx), eliminating CLI parameter overrides entirely. These CLI parameters are expected to be deprecated in the future, so investing in additional validation for them may not be worthwhile.
There was a problem hiding this comment.
Thanks for the context. Agree it may have existed before, but this refactor changes the precedence model to make CLI a first-class “highest priority” layer again (fixing #6567). Once CLI overrides are honored, lack of CLI-side validation becomes more user-visible and can lead to invalid runtime state (e.g. values below the safety floor) that config-path already protects against.
Even if CLI is planned to be deprecated, we still need it to be safe and consistent while it exists. The change here is low-cost: apply the same guardrail as config (max(3_000_000L, …)), so behavior is consistent across layers and we don’t regress safety/expectations.
If you prefer not to add validation now, could we at least (1) document the constraint in the CLI help, and (2) add a test to lock the desired behavior once CLI overrides are enabled? Otherwise we risk reintroducing "config is safe but CLI can bypass safety checks" inconsistencies.
| if (assigned.containsKey("--log-config")) { | ||
| PARAMETER.logbackPath = cmd.logbackPath; | ||
| } | ||
| if (!cmd.seedNodes.isEmpty()) { |
There was a problem hiding this comment.
Inconsistent "explicit CLI override" detection for seedNodes: applyCLIParams() uses isAssigned() for most options, but seed nodes are applied whenever cmd.seedNodes is non-empty. With the current positional mapping, this might be fine, but it breaks the principle "only explicitly passed options override config".
If you keep seed nodes positional, please document it clearly; otherwise, prefer making it a named option and gate it via isAssigned.
Beside, in the #6567 , @halibobo1205 has mentioned this related problem.
| public boolean eventSubscribe; | ||
|
|
||
| @Parameter(names = {"--p2p-disable"}, description = "Switch for p2p module initialization. " | ||
| + "(defalut: false)", arity = 1) |
There was a problem hiding this comment.
"defalut" --> "default"
| // ── Runtime parameters ────────────────────────── | ||
|
|
||
| @Parameter(names = {"--support-constant"}, description = "Support constant calling for TVM. " | ||
| + "(defalut: false)") |
There was a problem hiding this comment.
"defalut" --> "default"
|
|
||
| // local witness | ||
| public static final String LOCAL_WITNESS = "localwitness"; | ||
| public static final String LOCAL_WITNESS = "localwitness"; //private key |
There was a problem hiding this comment.
"//private key" --> "// private key"
| TronError.ErrCode.WITNESS_INIT); | ||
| } | ||
|
|
||
| public static void clearParam() { |
There was a problem hiding this comment.
CommonParameter.reset() is marked @VisibleForTesting and documented as "Test-only", yet Args.clearParam() calls it unconditionally.
What about also adding @VisibleForTesting for clearParam()?
| * Only assigned parameters override Config values. | ||
| */ | ||
| private static void applyCLIParams(CLIParameter cmd, JCommander jc) { | ||
| Map<String, ParameterDescription> assigned = jc.getParameters().stream() |
There was a problem hiding this comment.
assigned is collected into a Map<String, ParameterDescription> but only containsKey() is used. Consider collecting into a Set<String> instead to avoid unused values and reduce the chance of Collectors.toMap throwing if keys ever collide.
Set<String> assigned = jc.getParameters().stream()
.filter(ParameterDescription::isAssigned)
.map(ParameterDescription::getLongestName)
.collect(Collectors.toSet());
// Then use contains() instead of containsKey()
if (assigned.contains("--verbose")) { ... }
| @Setter | ||
| public static boolean ENERGY_LIMIT_HARD_FORK = false; | ||
|
|
||
| // ── Startup parameters ──────────────────────── |
There was a problem hiding this comment.
using "// -- Startup parameters --" instead of Unicode.
| @Getter | ||
| @Parameter(names = {"-h", "--help"}, help = true, description = "Show help message") | ||
| public boolean help = false; | ||
| // ── Flags (CLI + Config) ────────────────────── |
There was a problem hiding this comment.
--> // --Flags (CLI + Config) --
| @Parameter(names = {"--fast-forward"}) | ||
| @Getter | ||
| public boolean fastForward = false; | ||
| // ── Network / P2P ───────────────────────────── |
There was a problem hiding this comment.
using "// -- Network / P2P --"
| @Parameter(names = {"--keystore-factory"}, description = "running KeystoreFactory") | ||
| public boolean keystoreFactory = false; | ||
|
|
||
| // ── RPC / HTTP ──────────────────────────────── |
There was a problem hiding this comment.
using "// -- RPC / HTTP --"
| public int checkFrozenTime; // for test only | ||
| public int checkFrozenTime; // clearParam: 1 | ||
|
|
||
| // ── Committee parameters ────────────────────── |
There was a problem hiding this comment.
using "// -- Committee parameters --"
| public long forbidTransferToContract; //committee parameter | ||
| public long forbidTransferToContract; | ||
|
|
||
| // ── Netty ───────────────────────────────────── |
There was a problem hiding this comment.
using "// -- Netty --"
| public boolean version; | ||
| public long trxExpirationTimeInMilliseconds; | ||
|
|
||
| // ── Shielded / ZK ───────────────────────────── |
There was a problem hiding this comment.
using "// -- Shielded / ZK --"
| @NoArgsConstructor | ||
| public class CLIParameter { | ||
|
|
||
| // ── Startup parameters ────────────────────────── |
There was a problem hiding this comment.
using "// -- Startup parameters --"
| + "java-tron. (default: true)") | ||
| public String contractParseEnable; | ||
|
|
||
| // ── Runtime parameters ────────────────────────── |
There was a problem hiding this comment.
using "// -- Runtime parameters --"
Summary
@Parameterannotations fromCommonParameterinto a newCLIParameterclass, separating CLI parsing from runtime config stateArgs.setParam()into a clear 4-step flow: parse CLI →applyConfigParams→applyCLIParams→initLocalWitnessesWitnessInitializerinto three static methods (initFromCLIPrivateKey,initFromCFGPrivateKey,initFromKeystore), with routing logic moved toArgs.initLocalWitnessespassword,privateKey,witnessAddressfromCommonParameter— sensitive credentials are now passed directly as method parameters and never stored in global stateTest plan
./gradlew :framework:test --tests "org.tron.core.config.args.*"— all parameter tests pass./gradlew :framework:test— full framework tests pass